package py.com.alfa.escriba.web.services.impl;

import org.springframework.transaction.annotation.Transactional;

import py.com.alfa.escriba.exception.ErrorCode;
import py.com.alfa.escriba.exception.ServiceException;
import py.com.alfa.escriba.persistence.dao.LoginDAO;
import py.com.alfa.escriba.persistence.dto.UserDTO;
import py.com.alfa.escriba.web.rest.dto.UserResponseDTO;
import py.com.alfa.escriba.web.services.LoginService;

@Transactional(readOnly = true)
public class LoginServiceImpl implements LoginService {

	private LoginDAO login;
	private String mediaType;
	
	@Override
	public UserResponseDTO validUser(String userName, String clave) throws ServiceException {
		UserResponseDTO res = new UserResponseDTO();
		
		if (userName == null) {
			throw new ServiceException(ErrorCode.NO_DATA_FOUND,"login.not.user.info", userName);
		}
		
		UserDTO user = this.login.getUserByUserName(userName);
		if ( user == null ) {
			throw new ServiceException(ErrorCode.NO_DATA_FOUND,"login.not.user.error", userName);
		}
		
		if ( clave == null ) {
			throw new ServiceException(ErrorCode.VALIDATION_FAILED,"login.not.pwd.error");
		}
		if ( clave != null && !clave.equals(user.getPassword())) {
			throw new ServiceException(ErrorCode.VALIDATION_FAILED,"login.not.equal.pwd.error");
		}	
    
        res.setUser(user);
        res.setSrvs(this.login.getServiceByUser(user.getId()));
		
		if(res.getSrvs() ==null || res.getSrvs().isEmpty()) {
			throw new ServiceException(ErrorCode.VALIDATION_FAILED,"login.not.srv.error", userName);
		}
		return res;
	}

	@Override
	public String getMediaType() {
		return this.mediaType;
	}
	
	public void setMediaType(String mediaType) {
		this.mediaType = mediaType;
	}
	
	public LoginDAO getLogin() {
		return login;
	}

	public void setLogin(LoginDAO login) {
		this.login = login;
	}
	
}
